import { createStore, Store, useStore as useVuexStore } from "vuex";

import { IRootState, IStoreType } from "./type";
import { ISelectOptionType } from "@/components/form-module/type/type";
import loginModule from "./login/login";
import systemModule from "./system/system";
import analysisModule from "./analysis/analysis";
import { getPageList } from "@/service/main/system/system";

const store = createStore<IRootState>({
  state() {
    return {
      rolesOptions: [],
      departmentOptions: [],
      menuListTreeData: []
    };
  },
  mutations: {
    changeDepOptions(state, option: ISelectOptionType[]) {
      state.departmentOptions = option;
    },
    changeRoleOptions(state, options: ISelectOptionType[]) {
      state.rolesOptions = options;
    },
    changeMenuListTree(state, menuList: any[]) {
      state.menuListTreeData = menuList;
    }
  },
  actions: {
    async getSelectOptionsAction({ commit }) {
      const depRes = await getPageList("/department/list", {
        offset: 0,
        size: 100
      });
      const depOptions: ISelectOptionType[] = depRes.data.list.map(
        (item: any) => ({
          value: item.id,
          label: item.name
        })
      );
      commit("changeDepOptions", depOptions);
      const roleRes = await getPageList("/role/list", {
        offset: 0,
        size: 100
      });
      const roleOptions: ISelectOptionType[] = roleRes.data.list.map(
        (item: any) => ({
          value: item.id,
          label: item.name
        })
      );
      commit("changeRoleOptions", roleOptions);
      const menuList = await getPageList("/menu/list", {});
      commit("changeMenuListTree", menuList.data.list);
    }
  },
  modules: {
    login: loginModule,
    system: systemModule,
    analysis: analysisModule
  }
});

export function reloadMainPage() {
  store.dispatch("login/reloadLoginData");
}

export function useStore(): Store<IStoreType> {
  return useVuexStore();
}

export default store;
